/*
 * @lc app=leetcode.cn id=547 lang=java
 *
 * [547] 朋友圈
 */

// @lc code=start
class Solution {

    class UnionFind {
        public int count = 0;
        private int[] parent;
        private int[] sz;
        public UnionFind(int n) {
            count = n;
            parent = new int[n];
            sz = new int[n];
            for (int i = 0; i < n; i++) {
                parent[i] = i;
                sz[i] = 1;
            }
        }

        public int find(int p) {
            while (p != parent[p]) {
                parent[p] = parent[parent[p]]; //path compression by halving
                p = parent[p];
            }
            return p;
        }

        public void union(int p, int q) {
            int rootP = find(p);
            int rootQ = find(q);

            if (rootP == rootQ) 
                return ;

            if (sz[rootP] < sz[rootQ]) { //attach small to large
                parent[rootP] = rootQ;
                sz[rootQ] += sz[rootP];
            } else {
                parent[rootQ] = rootP;
                sz[rootP] += sz[rootQ];
            }

            count--;
        }
    }

    public int findCircleNum(int[][] M) {
        int n = M.length;

        UnionFind unionFind = new UnionFind(n);
        for (int i = 0; i < n -1; i++) {
            for (int j = i + 1; j < n; j++) {
                if (M[i][j] == 1) {
                    unionFind.union(i,j);
                }
            }
        }
        
        return unionFind.count;

    }
}
// @lc code=end

